1a2ddcc96e5b9c32c227ae69120fad1c60daac05
[lhc/web/wiklou.git] / includes / api / ApiQueryBase.php
1 <?php
2
3 /**
4 * Created on Sep 7, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 */
25
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( 'ApiBase.php' );
29 }
30
31 /**
32 * This is a base class for all Query modules.
33 * It provides some common functionality such as constructing various SQL
34 * queries.
35 *
36 * @ingroup API
37 */
38 abstract class ApiQueryBase extends ApiBase {
39
40 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
41
42 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
43 parent::__construct( $query->getMain(), $moduleName, $paramPrefix );
44 $this->mQueryModule = $query;
45 $this->mDb = null;
46 $this->resetQueryParams();
47 }
48
49 /**
50 * Get the cache mode for the data generated by this module. Override this
51 * in the module subclass.
52 *
53 * Public caching will only be allowed if *all* the modules that supply
54 * data for a given request return a cache mode of public.
55 */
56 public function getCacheMode( $params ) {
57 return 'private';
58 }
59
60 /**
61 * Blank the internal arrays with query parameters
62 */
63 protected function resetQueryParams() {
64 $this->tables = array();
65 $this->where = array();
66 $this->fields = array();
67 $this->options = array();
68 $this->join_conds = array();
69 }
70
71 /**
72 * Add a set of tables to the internal array
73 * @param $tables mixed Table name or array of table names
74 * @param $alias mixed Table alias, or null for no alias. Cannot be
75 * used with multiple tables
76 */
77 protected function addTables( $tables, $alias = null ) {
78 if ( is_array( $tables ) ) {
79 if ( !is_null( $alias ) ) {
80 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
81 }
82 $this->tables = array_merge( $this->tables, $tables );
83 } else {
84 if ( !is_null( $alias ) ) {
85 $tables = $this->getAliasedName( $tables, $alias );
86 }
87 $this->tables[] = $tables;
88 }
89 }
90
91 /**
92 * Get the SQL for a table name with alias
93 * @param $table string Table name
94 * @param $alias string Alias
95 * @return string SQL
96 */
97 protected function getAliasedName( $table, $alias ) {
98 return $this->getDB()->tableName( $table ) . ' ' . $alias;
99 }
100
101 /**
102 * Add a set of JOIN conditions to the internal array
103 *
104 * JOIN conditions are formatted as array( tablename => array(jointype,
105 * conditions) e.g. array('page' => array('LEFT JOIN',
106 * 'page_id=rev_page')) . conditions may be a string or an
107 * addWhere()-style array
108 * @param $join_conds array JOIN conditions
109 */
110 protected function addJoinConds( $join_conds ) {
111 if ( !is_array( $join_conds ) ) {
112 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
113 }
114 $this->join_conds = array_merge( $this->join_conds, $join_conds );
115 }
116
117 /**
118 * Add a set of fields to select to the internal array
119 * @param $value mixed Field name or array of field names
120 */
121 protected function addFields( $value ) {
122 if ( is_array( $value ) ) {
123 $this->fields = array_merge( $this->fields, $value );
124 } else {
125 $this->fields[] = $value;
126 }
127 }
128
129 /**
130 * Same as addFields(), but add the fields only if a condition is met
131 * @param $value mixed See addFields()
132 * @param $condition bool If false, do nothing
133 * @return bool $condition
134 */
135 protected function addFieldsIf( $value, $condition ) {
136 if ( $condition ) {
137 $this->addFields( $value );
138 return true;
139 }
140 return false;
141 }
142
143 /**
144 * Add a set of WHERE clauses to the internal array.
145 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
146 * the latter only works if the value is a constant (i.e. not another field)
147 *
148 * If $value is an empty array, this function does nothing.
149 *
150 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
151 * to "foo=bar AND baz='3' AND bla='foo'"
152 * @param $value mixed String or array
153 */
154 protected function addWhere( $value ) {
155 if ( is_array( $value ) ) {
156 // Sanity check: don't insert empty arrays,
157 // Database::makeList() chokes on them
158 if ( count( $value ) ) {
159 $this->where = array_merge( $this->where, $value );
160 }
161 } else {
162 $this->where[] = $value;
163 }
164 }
165
166 /**
167 * Same as addWhere(), but add the WHERE clauses only if a condition is met
168 * @param $value mixed See addWhere()
169 * @param $condition boolIf false, do nothing
170 * @return bool $condition
171 */
172 protected function addWhereIf( $value, $condition ) {
173 if ( $condition ) {
174 $this->addWhere( $value );
175 return true;
176 }
177 return false;
178 }
179
180 /**
181 * Equivalent to addWhere(array($field => $value))
182 * @param $field string Field name
183 * @param $value string Value; ignored if null or empty array;
184 */
185 protected function addWhereFld( $field, $value ) {
186 // Use count() to its full documented capabilities to simultaneously
187 // test for null, empty array or empty countable object
188 if ( count( $value ) ) {
189 $this->where[$field] = $value;
190 }
191 }
192
193 /**
194 * Add a WHERE clause corresponding to a range, and an ORDER BY
195 * clause to sort in the right direction
196 * @param $field string Field name
197 * @param $dir string If 'newer', sort in ascending order, otherwise
198 * sort in descending order
199 * @param $start string Value to start the list at. If $dir == 'newer'
200 * this is the lower boundary, otherwise it's the upper boundary
201 * @param $end string Value to end the list at. If $dir == 'newer' this
202 * is the upper boundary, otherwise it's the lower boundary
203 * @param $sort bool If false, don't add an ORDER BY clause
204 */
205 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
206 $isDirNewer = ( $dir === 'newer' );
207 $after = ( $isDirNewer ? '>=' : '<=' );
208 $before = ( $isDirNewer ? '<=' : '>=' );
209 $db = $this->getDB();
210
211 if ( !is_null( $start ) ) {
212 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
213 }
214
215 if ( !is_null( $end ) ) {
216 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
217 }
218
219 if ( $sort ) {
220 $order = $field . ( $isDirNewer ? '' : ' DESC' );
221 if ( !isset( $this->options['ORDER BY'] ) ) {
222 $this->addOption( 'ORDER BY', $order );
223 } else {
224 $this->addOption( 'ORDER BY', $this->options['ORDER BY'] . ', ' . $order );
225 }
226 }
227 }
228
229 /**
230 * Add an option such as LIMIT or USE INDEX. If an option was set
231 * before, the old value will be overwritten
232 * @param $name string Option name
233 * @param $value string Option value
234 */
235 protected function addOption( $name, $value = null ) {
236 if ( is_null( $value ) ) {
237 $this->options[] = $name;
238 } else {
239 $this->options[$name] = $value;
240 }
241 }
242
243 /**
244 * Execute a SELECT query based on the values in the internal arrays
245 * @param $method string Function the query should be attributed to.
246 * You should usually use __METHOD__ here
247 * @return ResultWrapper
248 */
249 protected function select( $method ) {
250 // getDB has its own profileDBIn/Out calls
251 $db = $this->getDB();
252
253 $this->profileDBIn();
254 $res = $db->select( $this->tables, $this->fields, $this->where, $method, $this->options, $this->join_conds );
255 $this->profileDBOut();
256
257 return $res;
258 }
259
260 /**
261 * Estimate the row count for the SELECT query that would be run if we
262 * called select() right now, and check if it's acceptable.
263 * @return bool true if acceptable, false otherwise
264 */
265 protected function checkRowCount() {
266 $db = $this->getDB();
267 $this->profileDBIn();
268 $rowcount = $db->estimateRowCount( $this->tables, $this->fields, $this->where, __METHOD__, $this->options );
269 $this->profileDBOut();
270
271 global $wgAPIMaxDBRows;
272 if ( $rowcount > $wgAPIMaxDBRows ) {
273 return false;
274 }
275 return true;
276 }
277
278 /**
279 * Add information (title and namespace) about a Title object to a
280 * result array
281 * @param $arr array Result array à la ApiResult
282 * @param $title Title
283 * @param $prefix string Module prefix
284 */
285 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
286 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
287 $arr[$prefix . 'title'] = $title->getPrefixedText();
288 }
289
290 /**
291 * Override this method to request extra fields from the pageSet
292 * using $pageSet->requestField('fieldName')
293 * @param $pageSet ApiPageSet
294 */
295 public function requestExtraData( $pageSet ) {
296 }
297
298 /**
299 * Get the main Query module
300 * @return ApiQuery
301 */
302 public function getQuery() {
303 return $this->mQueryModule;
304 }
305
306 /**
307 * Add a sub-element under the page element with the given page ID
308 * @param $pageId int Page ID
309 * @param $data array Data array à la ApiResult
310 * @return bool Whether the element fit in the result
311 */
312 protected function addPageSubItems( $pageId, $data ) {
313 $result = $this->getResult();
314 $result->setIndexedTagName( $data, $this->getModulePrefix() );
315 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
316 $this->getModuleName(),
317 $data );
318 }
319
320 /**
321 * Same as addPageSubItems(), but one element of $data at a time
322 * @param $pageId int Page ID
323 * @param $item array Data array à la ApiResult
324 * @param $elemname string XML element name. If null, getModuleName()
325 * is used
326 * @return bool Whether the element fit in the result
327 */
328 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
329 if ( is_null( $elemname ) ) {
330 $elemname = $this->getModulePrefix();
331 }
332 $result = $this->getResult();
333 $fit = $result->addValue( array( 'query', 'pages', $pageId,
334 $this->getModuleName() ), null, $item );
335 if ( !$fit ) {
336 return false;
337 }
338 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
339 $this->getModuleName() ), $elemname );
340 return true;
341 }
342
343 /**
344 * Set a query-continue value
345 * @param $paramName string Parameter name
346 * @param $paramValue string Parameter value
347 */
348 protected function setContinueEnumParameter( $paramName, $paramValue ) {
349 $paramName = $this->encodeParamName( $paramName );
350 $msg = array( $paramName => $paramValue );
351 $this->getResult()->disableSizeCheck();
352 $this->getResult()->addValue( 'query-continue', $this->getModuleName(), $msg );
353 $this->getResult()->enableSizeCheck();
354 }
355
356 /**
357 * Get the Query database connection (read-only)
358 * @return Database
359 */
360 protected function getDB() {
361 if ( is_null( $this->mDb ) ) {
362 $this->mDb = $this->getQuery()->getDB();
363 }
364 return $this->mDb;
365 }
366
367 /**
368 * Selects the query database connection with the given name.
369 * See ApiQuery::getNamedDB() for more information
370 * @param $name string Name to assign to the database connection
371 * @param $db int One of the DB_* constants
372 * @param $groups array Query groups
373 * @return Database
374 */
375 public function selectNamedDB( $name, $db, $groups ) {
376 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
377 }
378
379 /**
380 * Get the PageSet object to work on
381 * @return ApiPageSet
382 */
383 protected function getPageSet() {
384 return $this->getQuery()->getPageSet();
385 }
386
387 /**
388 * Convert a title to a DB key
389 * @param $title string Page title with spaces
390 * @return string Page title with underscores
391 */
392 public function titleToKey( $title ) {
393 // Don't throw an error if we got an empty string
394 if ( trim( $title ) == '' ) {
395 return '';
396 }
397 $t = Title::newFromText( $title );
398 if ( !$t ) {
399 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
400 }
401 return $t->getPrefixedDbKey();
402 }
403
404 /**
405 * The inverse of titleToKey()
406 * @param $key string Page title with underscores
407 * @return string Page title with spaces
408 */
409 public function keyToTitle( $key ) {
410 // Don't throw an error if we got an empty string
411 if ( trim( $key ) == '' ) {
412 return '';
413 }
414 $t = Title::newFromDbKey( $key );
415 // This really shouldn't happen but we gotta check anyway
416 if ( !$t ) {
417 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
418 }
419 return $t->getPrefixedText();
420 }
421
422 /**
423 * An alternative to titleToKey() that doesn't trim trailing spaces
424 * @param $titlePart string Title part with spaces
425 * @return string Title part with underscores
426 */
427 public function titlePartToKey( $titlePart ) {
428 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
429 }
430
431 /**
432 * An alternative to keyToTitle() that doesn't trim trailing spaces
433 * @param $keyPart string Key part with spaces
434 * @return string Key part with underscores
435 */
436 public function keyPartToTitle( $keyPart ) {
437 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
438 }
439
440 public function getPossibleErrors() {
441 return array_merge( parent::getPossibleErrors(), array(
442 array( 'invalidtitle', 'title' ),
443 array( 'invalidtitle', 'key' ),
444 ) );
445 }
446
447 /**
448 * Get version string for use in the API help output
449 * @return string
450 */
451 public static function getBaseVersion() {
452 return __CLASS__ . ': $Id$';
453 }
454 }
455
456 /**
457 * @ingroup API
458 */
459 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
460
461 private $mIsGenerator;
462
463 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
464 parent::__construct( $query, $moduleName, $paramPrefix );
465 $this->mIsGenerator = false;
466 }
467
468 /**
469 * Switch this module to generator mode. By default, generator mode is
470 * switched off and the module acts like a normal query module.
471 */
472 public function setGeneratorMode() {
473 $this->mIsGenerator = true;
474 }
475
476 /**
477 * Overrides base class to prepend 'g' to every generator parameter
478 * @param $paramName string Parameter name
479 * @return string Prefixed parameter name
480 */
481 public function encodeParamName( $paramName ) {
482 if ( $this->mIsGenerator ) {
483 return 'g' . parent::encodeParamName( $paramName );
484 } else {
485 return parent::encodeParamName( $paramName );
486 }
487 }
488
489 /**
490 * Execute this module as a generator
491 * @param $resultPageSet ApiPageSet: All output should be appended to
492 * this object
493 */
494 public abstract function executeGenerator( $resultPageSet );
495 }